#pragma once
#include <iostream>
#include <sys/types.h>
#include <unistd.h>
#include <cstring>
#include <ctime>
#include <cstdarg>
#include <cstdio>
using namespace std;

// 日志等级
enum level
{
    Debug,
    Info,
    Warning,
    Error,
    Fatal,
    Unknow
};

string get_lv_str(int level)
{
    switch (level)
    {
    case Debug:
        return "Debug";
    case Info:
        return "Info";
    case Warning:
        return "Warning";
    case Error:
        return "Error";
    case Fatal:
        return "Fatal";
    default:
        return "Unknow";
    }
}

string get_time_str()
{
    time_t t = time(nullptr);
    struct tm* s_tm = localtime(&t);

    // int tm_sec;			/* Seconds.	[0-60] (1 leap second) */
    // int tm_min;			/* Minutes.	[0-59] */
    // int tm_hour;			/* Hours.	[0-23] */
    // int tm_mday;			/* Day.		[1-31] */
    // int tm_mon;			/* Month.	[0-11] */
    // int tm_year;			/* Year	- 1900.  */
    // int tm_wday;			/* Day of week.	[0-6] */
    // int tm_yday;			/* Days in year.[0-365]	*/
    // int tm_isdst;			/* DST.		[-1/0/1]*/

    string time_str;
    time_str += to_string(s_tm->tm_year + 1900) + "-" + to_string(s_tm->tm_mon + 1) + "-" + to_string(s_tm->tm_mday) + " " + to_string(s_tm->tm_hour) + ":" + to_string(s_tm->tm_min) + ":" + to_string(s_tm->tm_sec);
    return time_str;
}

// 输出日志等级、时间、pid、消息
void log_message(int level, const char *format, ...)
{
    string left;
    string level_str = get_lv_str(level);
    string time_str = get_time_str();
    left += "[" + level_str + "] " + "[" + time_str + "] " + "[" + to_string(getpid()) + "] ";

    string right;
    va_list vl;
    va_start(vl, format);
    char buff[1024];
    vsnprintf(buff, sizeof(buff), format, vl);
    right += buff;
    va_end(vl);
    
    //cout << left << right << endl;
    FILE* file = fopen("logmsg.log", "a");
    if(file == nullptr)
    {
        return ;
    }
    fprintf(file, "%s%s\n", left.c_str(), right.c_str());
    fclose(file);
}